
// src/stores/modules/authStore.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userAPI } from '@/api/user'
import { ElMessage } from 'element-plus'


// 图标名称标准化函数（统一处理）
const normalizeIconName = (icon) => {
    if (!icon) return 'default'
    return icon.toString()
        .toLowerCase()
        .replace(/^icon-?/, '')
        .replace(/-?icon$/, '')
        .replace(/\s+/g, '-')
        .trim()
}

export const useAuthStore = defineStore('auth', () => {
    const token = ref(localStorage.getItem('token') || null)
    const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || 'null'))
    const userACLInfo = ref(JSON.parse(localStorage.getItem('userACLInfo') || 'null'))
    const menuList = ref(JSON.parse(localStorage.getItem('menuList') || '[]'))
    const permissions = ref(JSON.parse(localStorage.getItem('permissions') || '[]'))
    const isLoading = ref(false)
    const error = ref(null)

    // 安全的JSON解析
    const safeJsonParse = (str, defaultValue) => {
        try {
            return str ? JSON.parse(str) : defaultValue
        } catch {
            return defaultValue
        }
    }

    // 初始化时重新解析本地存储
    const initializeFromLocalStorage = () => {
        token.value = localStorage.getItem('token')
        userInfo.value = safeJsonParse(localStorage.getItem('userInfo'), null)
        userACLInfo.value = safeJsonParse(localStorage.getItem('userACLInfo'), null)
        menuList.value = safeJsonParse(localStorage.getItem('menuList'), [])
        permissions.value = safeJsonParse(localStorage.getItem('permissions'), [])
    }

    // 优化后的菜单转换函数
    const transformMenu = (menu) => {
        if (!menu || typeof menu !== 'object') {
            console.warn('Invalid menu item:', menu)
            return { path: '', name: 'Invalid Menu', icon: 'default' }
        }

        const transformed = {
            path: menu.path || '',
            name: menu.name || 'Unnamed Menu',
            icon: normalizeIconName(menu.icon),
            children: []
        }

        // 递归处理子菜单
        if (Array.isArray(menu.children)) {
            transformed.children = menu.children.map(transformMenu)
        }

        return transformed
    }

    // 根据userACLInfo生成菜单列表（增强版）
    const generateMenuList = () => {
        try {
            let menus = []

            if (userACLInfo.value?.menuTree?.length) {
                console.log('原始菜单数据:', userACLInfo.value.menuTree)
                menus = userACLInfo.value.menuTree.map(transformMenu)
            } else {
                console.warn('使用默认菜单配置')
                menus = ALL_MENU_ITEMS.map(transformMenu)
            }

            // 确保菜单数据有效
            const validatedMenus = menus.filter(menu => menu.path)
            console.log('处理后菜单数据:', validatedMenus)

            // 保存到本地存储和状态
            localStorage.setItem('menuList', JSON.stringify(validatedMenus))
            return validatedMenus
        } catch (err) {
            console.error('生成菜单列表错误:', err)
            return ALL_MENU_ITEMS.map(transformMenu)
        }
    }

    // 登录逻辑（增强版）
    const loginByPassword = async (username, password) => {
        try {
            isLoading.value = true
            error.value = null

            const response = await userAPI.loginByPassword({ username, password })
            const data = response.data?.data || {}

            if (!data.token) {
                throw new Error('登录失败：未获取到token')
            }

            // 更新用户状态
            token.value = data.token
            userInfo.value = {
                id: data.userEntity?.id,
                username: data.userEntity?.username,
                name: data.userEntity?.realName,
                role: data.userEntity?.userType,
                phone: data.userEntity?.mobile,
                email: data.userEntity?.email
            }

            // 获取并处理权限信息
            await fetchCurrentUser()

            // 生成并验证菜单
            const generatedMenu = generateMenuList()
            if (!generatedMenu.length) {
                console.warn('生成的菜单为空，使用默认菜单')
                menuList.value = ALL_MENU_ITEMS.map(transformMenu)
            } else {
                menuList.value = generatedMenu
            }

            // 持久化数据
            localStorage.setItem('token', token.value)
            localStorage.setItem('userInfo', JSON.stringify(userInfo.value))

            console.log('登录成功，当前菜单:', menuList.value)
            return { success: true, user: userInfo.value }
        } catch (err) {
            error.value = err.message || '登录失败'
            console.error('登录错误:', err)
            return { success: false, error: err.message }
        } finally {
            isLoading.value = false
        }
    }

    const loginByCode = async (phone, code) => {
        try {
            isLoading.value = true
            error.value = null

            const response = await userAPI.loginByCode({ phone, code })
            const data = response.data?.data || {}

            if (response.data?.code !== "200") {
                throw new Error(response.data?.message || 'Login failed')
            }

            token.value = data.token || null
            userInfo.value = {
                username: data.userEntity?.username,
                name: data.userEntity?.realName,
                role: data.userEntity?.userType,
                phone: data.userEntity?.mobile,
                email: data.userEntity?.email
            }

            // 获取用户权限信息
            await fetchCurrentUser()

            // 生成菜单列表
            menuList.value = generateMenuList()

            localStorage.setItem('token', token.value || '')
            localStorage.setItem('userInfo', JSON.stringify(userInfo.value))

            ElMessage.success('登录成功')
            console.log('Code login successful - menu list:', menuList.value)
            return { success: true, user: userInfo.value }
        } catch (err) {
            error.value = err.message || 'Login failed'
            ElMessage.error(err.message)
            console.error('Code login error:', err)
            return { success: false, error: err.message }
        } finally {
            isLoading.value = false
        }
    }

    const fetchCurrentUser = async () => {
        try {
            const response = await userAPI.getCurrentUser()
            userACLInfo.value = response.data || {}
            localStorage.setItem('userACLInfo', JSON.stringify(userACLInfo.value))
            return userACLInfo.value
        } catch (err) {
            error.value = err.message || 'Failed to fetch user info'
            throw err
        }
    }

    const logout = async () => {
        try {
            await userAPI.logout(userInfo.value?.id)
        } catch (err) {
            console.error('退出登录错误:', err)
        }
        token.value = null
        userInfo.value = null
        userACLInfo.value = null
        menuList.value = []
        permissions.value = []

        // 清除所有相关存储
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        localStorage.removeItem('userACLInfo')
        localStorage.removeItem('permissions')
        localStorage.removeItem('menuList')
        sessionStorage.removeItem('wpkreporter:frmid')

        ElMessage.success('退出成功')
    }

    const isAuthenticated = () => {
        return !!token.value
    }

    const hasPermission = (permission) => {
        return permissions.value.includes(permission)
    }

    const fetchUserProfile = async () => {
        try {
            const response = await userAPI.getUserPersionalInfo()
            const data = response.data || {}

            userInfo.value = {
                ...userInfo.value,
                username: data.username || '',
                name: data.realName || '',
                phone: data.mobile || '',
                email: data.email || '',
                userType: data.userType || '',

                authStatus: data.authStatus || ''
            }

            localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
            return userInfo.value
        } catch (err) {
            error.value = err.message || 'Failed to fetch profile'
            throw err
        }
    }

    const updateUserProfile = async (profileData) => {
        try {
            isLoading.value = true
            const response = await userAPI.updateUser({
                id: userInfo.value?.id,
                ...profileData
            })

            // 更新本地存储的用户信息
            userInfo.value = {
                ...userInfo.value,
                ...profileData
            }

            localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
            ElMessage.success('个人信息更新成功')
            return response.data
        } catch (err) {
            error.value = err.message || 'Update failed'
            ElMessage.error('更新失败: ' + err.message)
            throw err
        } finally {
            isLoading.value = false
        }
    }

    // 初始化时从本地存储加载数据
    initializeFromLocalStorage()

    return {
        token,
        userInfo,
        userACLInfo,
        menuList,
        permissions,
        isLoading,
        error,
        loginByPassword,
        loginByCode,
        fetchCurrentUser,
        logout,
        isAuthenticated,
        hasPermission,
        fetchUserProfile,
        updateUserProfile
    }
})